package freedom.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.util.StringUtils;

/**
 * @author Charlie Email:tingfangcao@163.com
 * @date 2020/08/14
 */
public class ExampleMatcherUtils {
    public static ExampleMatcher withIgnoreBlankValues(ExampleMatcher em, Object bean) {
        PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(bean.getClass());
        List<String> ignoredPaths = new ArrayList<>();
        for (PropertyDescriptor pd : pds) {
            if (pd.getPropertyType().equals(String.class)) {

                Object value = null;
                try {
                    value = pd.getReadMethod().invoke(bean);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                if (!StringUtils.hasText((String)value)) {
                    ignoredPaths.add(pd.getName());
                }
            }
        }
        if (ignoredPaths.size() > 0)
            return em.withIgnorePaths(ignoredPaths.toArray(new String[ignoredPaths.size()]));
        else
            return em;
    }
}
